package net.gd.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import net.gd.domain.UdfInfo;
import net.gd.utils.Constants;
import net.gd.utils.CustomizeSpringContext;

public class UdfInfoDaoImpl extends JdbcTemplate implements UdfInfoDao {

  private static Logger logger = Logger.getLogger(UdfInfoDaoImpl.class);

  private DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");


  public static void main(String[] args) throws Exception {
    UdfInfoDao dao = (UdfInfoDao) CustomizeSpringContext.getBean(UdfInfoDaoImpl.class);
//    UdfInfo info = new UdfInfo();
//    info.setCreateUser("cxq");
//    info.setLangType("scala");
//    info.setUdfContent("(s:String) => s.length()");
//    info.setUdfName("strLen2");
//    info.setUdfId("20180206231127253");
//
//    String udfId = dao.saveOrUpdate(info);
    
    
    System.out.println(dao.get("20180206231127253"));
    System.out.println(dao.list("20180206231009083", "str"));
  }

  @Override
  public String saveOrUpdate(UdfInfo udfInfo) throws Exception {
    StringBuilder sql = new StringBuilder();
    if (udfInfo.getUdfId() != null) {
      // update
      sql.append("update udf_info set ");
      if (udfInfo.getLangType() != null) {
        sql.append("lang_type = '").append(udfInfo.getLangType()).append("',");
      }
      if (udfInfo.getUdfContent() != null) {
        sql.append("udf_content = '").append(udfInfo.getUdfContent()).append("',");
      }
      if (udfInfo.getUdfName() != null) {
        sql.append("udf_name = '").append(udfInfo.getUdfName()).append("',");
      }
      if (udfInfo.getCreateUser() != null) {
        sql.append("create_user = '").append(udfInfo.getCreateUser()).append("',");
      }
      sql.append("update_datetime='");
      sql.append(new SimpleDateFormat(Constants.DATETIME_FORMAT).format(new Date()));
      sql.append("' ");
      sql.append(" where udf_id='").append(udfInfo.getUdfId()).append("'");
      logger.info("update sql: " + sql.toString());
      this.execute(sql.toString());
      return udfInfo.getUdfId();
    } else {
      // save
      String udfId = df.format(new Date());
      sql.append("insert into udf_info");
      sql.append(
          "(udf_id,udf_name,lang_type,udf_content,create_user,create_datetime,update_datetime)");
      sql.append("values(?,?,?,?,?,?,?)");
      logger.info("insert sql: " + sql.toString());
      this.update(sql.toString(), udfId, udfInfo.getUdfName(), udfInfo.getLangType(),
          udfInfo.getUdfContent(), udfInfo.getCreateUser(), new Date(), new Date());
      return udfId;
    }

  }


  @Override
  public UdfInfo get(String modelId) throws Exception {

    String sql =
        "select udf_id,udf_name,lang_type,udf_content,create_user,create_datetime,update_datetime"
            + " from udf_info where udf_id = ?";
    UdfInfo info = null;
    try {
      info = this.queryForObject(sql, new Object[] {modelId}, infoMapper);
    } catch (Exception e) {
      return null;
    }
    return info;
  }

  private RowMapper<UdfInfo> infoMapper = new RowMapper<UdfInfo>() {

    @Override
    public UdfInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
      UdfInfo info = new UdfInfo();
      info.setUdfId(rs.getString("udf_id"));
      info.setUdfName(rs.getString("udf_name"));
      info.setLangType(rs.getString("lang_type"));
      info.setUdfContent(rs.getString("udf_content"));
      info.setCreateUser(rs.getString("create_user"));
      info.setCreateDatetime(rs.getDate("create_datetime"));
      info.setUpdateDatetime(rs.getDate("update_datetime"));
      return info;
    }
  };

  @Override
  public List<UdfInfo> list(String modelId, String modelName) throws Exception {

    String sql =
        "select udf_id,udf_name,lang_type,udf_content,create_user,create_datetime,update_datetime"
            + " from udf_info where 1 = 1 ";
    if (StringUtils.isNotBlank(modelId)) {
      sql += " and udf_id = '" + modelId + "'";
    } else if (StringUtils.isNotBlank(modelName)) {
      sql += " and udf_name like '%" + modelName + "%'";
    }
    List<UdfInfo> list = new ArrayList<UdfInfo>();
    try {
      list = this.query(sql, infoMapper);
    } catch (Exception e) {
      return null;
    }
    return list;
  }



}
